import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import DBSCAN
import matplotlib.patches as patches
import pickle


# 设置参数
center = (0, 0)  # 圆形区域中心坐标
radius = 20  # 圆形区域半径


# 从文件中读取之前保存的 Matern 簇数据
with open("matern_cluster_square_data.pkl", "rb") as f:
    points, parent_points_x, parent_points_y, square_markers = pickle.load(f)

# 为 square_indices 对应的点画正方形，并绘制同心圆
square_indices = np.where(square_markers == 1)[0]
square_points = points[square_indices]
# print(square_points)
# 创建一个包含两个子图的窗口
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(20, 8))


# 获取离坐标原点最近的两个点的距离，以此距离作为半径画圆（修改后的关键逻辑）
distances = np.sqrt(
    (square_points[:, 0] - center[0]) ** 2 + (square_points[:, 1] - center[1]) ** 2
)
sorted_indices = np.argsort(distances)
radius_w = distances[
    sorted_indices[5]
]  # 取第二个最近的距离作为半径（索引从 0 开始，所以取 1）
circle1 = plt.Circle(center, radius_w, fill=False, color="black")
ax1.add_patch(circle1)
circle2 = plt.Circle(center, radius_w, fill=False, color="black")
ax2.add_patch(circle2)


# 找出圆内的点
in_circle = (points[:, 0] - center[0]) ** 2 + (
    points[:, 1] - center[1]
) ** 2 <= radius_w**2


# 在第一个子图中绘制模拟 Matern 簇过程的图形
ax1.scatter(points[:, 0], points[:, 1], label="All Points")
parent_points = np.array(
    [(parent_points_x[i], parent_points_y[i]) for i in range(len(parent_points_x))]
)
ax1.scatter(
    parent_points[:, 0],
    parent_points[:, 1],
    marker="^",
    s=50,
    c="green",
    label="Cluster Centers",
)
ax1.set_xlim(center[0] - radius, center[0] + radius)
ax1.set_ylim(center[1] - radius, center[1] + radius)
ax2.set_xlim(center[0] - radius, center[0] + radius)
ax2.set_ylim(center[1] - radius, center[1] + radius)
ax1.set_aspect("equal", adjustable="box")
ax1.set_title("Matern Cluster Process")
ax1.set_xlabel("X-axis")
ax1.set_ylabel("Y-axis")
ax1.legend()


# 剔除圆内的点，获取用于聚类的点
points_for_clustering = points[~in_circle]


# 使用 DBSCAN 进行聚类
dbscan = DBSCAN(eps=2.5, min_samples=3)  # 这里的参数可根据实际情况调整
clusters = dbscan.fit_predict(points_for_clustering)


# 提取不同簇的点和噪声点，注意要根据 points_for_clustering 的索引对应回原 points 的索引来处理
unique_clusters = np.unique(clusters)


cluster_sets_for_draw = {cluster: [] for cluster in unique_clusters}


# 存储用于绘图的点
for i, cluster_label in enumerate(clusters):
    if cluster_label != -1:
        # 根据在 points_for_clustering 中的索引，找到在原 points 中的对应点
        index_in_original = np.where(~in_circle)[0][i]
        cluster_sets_for_draw[cluster_label].append(points[index_in_original])
    else:
        # 噪声点同样要找到在原 points 中的对应索引
        noise_indices = np.where(clusters == -1)[0]
        noise_indices_in_original = np.where(~in_circle)[0][noise_indices]
        for idx in noise_indices_in_original:
            cluster_sets_for_draw[-1].append(points[idx])


# 标注 Willie
ax1.scatter(0, 0, marker="+", s=100, c="r", label="Willie")
ax2.scatter(0, 0, marker="+", s=100, c="r", label="Willie")


# 将圆内的点变红
ax1.scatter(points[in_circle, 0], points[in_circle, 1], c="red")
ax2.scatter(points[in_circle, 0], points[in_circle, 1], c="red")


# 为每个簇绘制圆（新添加的逻辑）
for cluster_label, cluster_points in cluster_sets_for_draw.items():
    cluster_points = np.array(cluster_points)
    if cluster_label != -1:
        ax2.scatter(
            cluster_points[:, 0],
            cluster_points[:, 1],
            label=f"Cluster {cluster_label}",
        )
        # center_x = np.mean(cluster_points[:, 0])
        # center_y = np.mean(cluster_points[:, 1])
        # center_tuple = (center_x, center_y)
        # distances = np.sqrt(
        #     (cluster_points[:, 0] - center_x) ** 2
        #     + (cluster_points[:, 1] - center_y) ** 2
        # )
        # radius = np.max(distances)
        # circle = plt.Circle(center_tuple, radius, fill=False, color="blue")
        # ax2.add_patch(circle)
    else:
        ax2.scatter(
            cluster_points[:, 0],
            cluster_points[:, 1],
            label="Noise Points",
            marker="x",
            c="gray",
        )

for cluster_label, cluster_points in cluster_sets_for_draw.items():
    cluster_points = np.array(cluster_points)
    if cluster_label != -1:
        # 找出在 points_for_clustering 中属于该簇的索引
        indices_in_cluster = np.where(clusters == cluster_label)[0]
        # 找出在原始 points 中对应的索引
        indices_in_original = np.where(~in_circle)[0][indices_in_cluster]
        # 找出属于该簇的 square_markers 标记
        cluster_square_markers = square_markers[indices_in_original]
        # 找出该簇中带正方形的点
        square_points_DB = cluster_points[cluster_square_markers == 1]
        # 找出该簇中不带正方形的点
        no_square_points_DB = cluster_points[cluster_square_markers == 0]

        # 为带正方形的点绘制圆
        if len(square_points_DB) > 0:
            center_x = np.mean(square_points_DB[:, 0])
            center_y = np.mean(square_points_DB[:, 1])
            center_tuple = (center_x, center_y)
            distances = np.sqrt(
                (square_points_DB[:, 0] - center_x) ** 2
                + (square_points_DB[:, 1] - center_y) ** 2
            )
            radius = np.max(distances)
            circle = plt.Circle(center_tuple, radius, fill=False, color="blue")
            ax2.add_patch(circle)

        # 为不带正方形的点绘制圆
        if len(no_square_points_DB) > 0:
            center_x = np.mean(no_square_points_DB[:, 0])
            center_y = np.mean(no_square_points_DB[:, 1])
            center_tuple = (center_x, center_y)
            distances = np.sqrt(
                (no_square_points_DB[:, 0] - center_x) ** 2
                + (no_square_points_DB[:, 1] - center_y) ** 2
            )
            radius = np.max(distances)
            circle = plt.Circle(center_tuple, radius, fill=False, color="orange")
            ax2.add_patch(circle)
        # center_x = np.mean(cluster_points[:, 0])
        # center_y = np.mean(cluster_points[:, 1])
        # center_tuple = (center_x, center_y)
        # distances = np.sqrt(
        #     (cluster_points[:, 0] - center_x) ** 2
        #     + (cluster_points[:, 1] - center_y) ** 2
        # )
        # radius = np.max(distances)
        # circle = plt.Circle(center_tuple, radius, fill=False, color="blue")
        # ax2.add_patch(circle)


for x, y in square_points:
    # 创建新的 Rectangle 实例
    rect1 = patches.Rectangle(
        (x - 0.5, y - 0.5),
        1,
        1,
        linewidth=1,
        edgecolor="blue",
        facecolor="none",
    )
    ax1.add_patch(rect1)
    rect2 = patches.Rectangle(
        (x - 0.5, y - 0.5),
        1,
        1,
        linewidth=1,
        edgecolor="blue",
        facecolor="none",
    )
    ax2.add_patch(rect2)


# 计算所有带正方形的点到坐标原点的距离，并从大到小排序
distances = np.sqrt(square_points[:, 0] ** 2 + square_points[:, 1] ** 2)
sorted_distances = np.sort(distances)[::-1]


# 在 ax1 中画同心圆，圆心为坐标原点，半径为 sorted_distances 中的数据
for dist in sorted_distances:
    circle = plt.Circle(center, dist, fill=False, color="blue", linestyle="dashed")
    ax1.add_patch(circle)


ax2.set_aspect("equal", adjustable="box")
ax2.set_title("Matern Cluster Process with DBSCAN Clustering")
ax2.set_xlabel("X-axis")
ax2.set_ylabel("Y-axis")
ax2.legend(loc="upper right", fontsize="small")


###########################
# 计算AoI的逻辑


plt.show()
